package sb.web;

import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import sb.entity.Partner;

/**
 *
 * @author Pavel
 */
@ManagedBean
@RequestScoped
public class PartnerManagedBean extends Partner {

	private static final long serialVersionUID = 1L;
	
	@PersistenceContext
    EntityManager em;
    @Resource
    UserTransaction ut;
	
	private String parentName = "";
	public void setParentName(String value) {
		parentName = value;
	}
	public String getParentName() {
		return parentName;
	}
	
    @PostConstruct
    public void init() {
        FacesContext facesContext = FacesContext.getCurrentInstance();

        Map<String, String> parameterMap = facesContext.getExternalContext().getRequestParameterMap();

        String stringId = parameterMap.get("id");

        if (stringId != null) {
            id = Long.decode(stringId);
			Partner partner = (Partner) em.createNamedQuery("partnerFindById")
					.setParameter("id", id)
					.getSingleResult();
			
			code = partner.getCode();
			name = partner.getName();
			isFolder = partner.getIsFolder();
			deletionMark = partner.getDeletionMark();
			parentId = partner.getParentId();
			
			try {
				Partner parent = (Partner) em.createNamedQuery("partnerFindById")
						.setParameter("id", parentId)
						.getSingleResult();
				parentName = parent.getName();
			} catch (NoResultException e) {
			}
			
        }
    }

    public void save() throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
        
        ut.begin();
        
		Partner partner;
		
		if (id == null) {
			partner = new Partner();
		} else {
			partner = (Partner) em.createNamedQuery("partnerFindById")
					.setParameter("id", id)
					.getSingleResult();
		}
		
		partner.setCode(code);
		partner.setName(name);
		partner.setDeletionMark(deletionMark);
		partner.setIsFolder(isFolder);
		partner.setParentId(parentId);
		
		if (id == null) {
			em.persist(partner);
		}
        
        ut.commit();
    }

    /**
     * Creates a new instance of PartnerManagedBean
     */
    public PartnerManagedBean() {
    }
}
